/**
 * OSAmI: Open Source Ambient Intelligence
 * Copyright (C) 2010 UJF.
 * Contact: osami-general@osami-commons.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 */
package org.osami.gateway.mediator.alarm.internal;

import org.osami.gateway.alarm.AlarmImpl;
import org.osami.gateway.alarm.IAlarm;
import org.osami.gateway.storage.IAlarmStorage;
import org.osgi.service.log.LogService;

import fr.liglab.adele.cilia.CiliaException;
import fr.liglab.adele.cilia.Data;

public class ProcessorAlarmStorage {

	private LogService logger;
	private IAlarmStorage storage;

	/**
	 * Store the Alarm triggered by drools.
	 * @throws CiliaException if the data does not contain an IAlarm
	 */
	public Data process(Data data) throws CiliaException {
		IAlarm alarm;
		try {
            if (data.getContent() instanceof IAlarm) {
                alarm = (IAlarm) data.getContent();
            } else {
                // Try to produce an Alarm nevertheless (I'm 95% sure that this will fail ...)
                alarm = new AlarmImpl(data.getAllData());
            }
		} catch (Exception e) {
			logger.log(LogService.LOG_WARNING, "Cannot get The IAlarm from the data ! bad data : " + data.toString(), e);
			throw new CiliaException("Cannot get The IAlarm from the data ! bad data: " + e.getMessage());
		}
		//Store the alarm by using the storage service
		try {
			System.out.println(alarm.getMessage());
			storage.store(alarm);
		} catch (Exception e) {
			logger.log(LogService.LOG_ERROR, "An Exception occured while storing the data: " + e.getMessage(), e);
		}
		
		return data;
	}

}
